package com.campus.campusdelivery.controller;

import com.campus.campusdelivery.dto.ApiResponse;
import com.campus.campusdelivery.dto.CreateOrderRequest;
import com.campus.campusdelivery.dto.OrderDto;
import com.campus.campusdelivery.dto.StatsDto;
import com.campus.campusdelivery.service.OrderService;
import com.campus.campusdelivery.util.UserContextUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class OrderController {
    
    private final OrderService orderService;
    private final UserContextUtil userContextUtil;
    
    @GetMapping("/test")
    public ApiResponse<String> testEndpoint() {
        return ApiResponse.success("订单服务正常工作");
    }
    
    @GetMapping("/test-pay/{id}")
    public ApiResponse<String> testPayEndpoint(@PathVariable Long id) {
        return ApiResponse.success("支付测试端点工作正常，订单ID: " + id);
    }
    
    @GetMapping("/my")
    public ApiResponse<Page<OrderDto>> getMyOrders(Pageable pageable) {
        try {
            Long userId = userContextUtil.getCurrentUserId();
            Page<OrderDto> orders = orderService.getOrdersByUserId(userId, pageable);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/merchant")
    public ApiResponse<Page<OrderDto>> getMerchantOrders(Pageable pageable) {
        try {
            Long userId = userContextUtil.getCurrentUserId();
            // TODO: 根据用户ID获取商家ID
            Page<OrderDto> orders = orderService.getOrdersByMerchantId(userId, pageable);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/delivery")
    public ApiResponse<Page<OrderDto>> getDeliveryOrders(Pageable pageable) {
        try {
            Long userId = userContextUtil.getCurrentUserId();
            Page<OrderDto> orders = orderService.getOrdersByDeliveryPersonId(userId, pageable);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/pending")
    public ApiResponse<Page<OrderDto>> getPendingOrders(Pageable pageable) {
        try {
            Page<OrderDto> orders = orderService.getPendingOrders(pageable);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public ApiResponse<OrderDto> getOrderById(@PathVariable Long id) {
        try {
            OrderDto order = orderService.getOrderById(id);
            return ApiResponse.success(order);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PostMapping
    public ApiResponse<OrderDto> createOrder(@Valid @RequestBody CreateOrderRequest orderRequest) {
        try {
            Long userId = userContextUtil.getCurrentUserId();
            OrderDto order = orderService.createOrder(userId, orderRequest);
            return ApiResponse.success("订单创建成功", order);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateOrderStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            orderService.updateOrderStatus(id, status);
            return ApiResponse.success("订单状态更新成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/cancel")
    public ApiResponse<Void> cancelOrder(@PathVariable Long id) {
        try {
            orderService.cancelOrder(id);
            return ApiResponse.success("订单取消成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/pay")
    public ApiResponse<Void> payOrder(@PathVariable Long id) {
        try {
            orderService.payOrder(id);
            return ApiResponse.success("支付成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/accept")
    public ApiResponse<Void> acceptOrder(@PathVariable Long id) {
        try {
            orderService.acceptOrder(id);
            return ApiResponse.success("接单成功", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/start-delivery")
    public ApiResponse<Void> startDelivery(@PathVariable Long id) {
        try {
            orderService.startDelivery(id);
            return ApiResponse.success("开始配送", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @PutMapping("/{id}/complete")
    public ApiResponse<Void> completeDelivery(@PathVariable Long id) {
        try {
            orderService.completeDelivery(id);
            return ApiResponse.success("配送完成", null);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/today-stats")
    public ApiResponse<StatsDto> getTodayStats() {
        try {
            // 暂时返回默认统计，避免500错误
            StatsDto stats = new StatsDto();
            return ApiResponse.success(stats);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @GetMapping("/recent")
    public ApiResponse<List<OrderDto>> getRecentOrders(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<OrderDto> orders = orderService.getRecentOrders(limit);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
